package com.sensetime.bi.senselink.server.rtsp.session;

import com.sensetime.bi.senselink.server.entity.Player;
import io.netty.channel.Channel;
import io.netty.util.Attribute;
import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.ConcurrentHashMap;

import static com.sensetime.bi.senselink.server.constant.Constant.SESSION_ID;

@Getter
@Setter
public class SessionManager {
    private static final ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();
    private static final RtspSessionIdFactory sessionIdFactory = new SimpleRandomIdFactory();

    public static void createPlayerSession(Channel channel) {
        Attribute<String> sessionAttr = channel.attr(SESSION_ID);
        if (sessionAttr.get() == null) {
            // 新的会话
            String sessionId = sessionIdFactory.createSessionId();
            channel.attr(SESSION_ID).set(sessionId);
        }
        String sessionId = sessionAttr.get();
        Session session = new Session();
        Player player = new Player();
        player.setConnection(channel);

        session.setPlayer(player);
        session.setSessionId(sessionId);

        sessionMap.put(sessionId, session);
    }


    public static Session getSession(String sessionId) {
        return sessionMap.get(sessionId);
    }
}
